package com.restaurant.springboot.controller;


import com.restaurant.springboot.annotation.TokenAuth;
import com.restaurant.springboot.entity.*;
import com.restaurant.springboot.entity.vo.OrderItemVO;
import com.restaurant.springboot.entity.vo.OrderVO;
import com.restaurant.springboot.service.*;
import com.restaurant.springboot.utils.RespCode;
import com.restaurant.springboot.utils.RespEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author jack
 * @Date:2019/7/29 14:12
 */
@RestController
@RequestMapping("/api/order")
public class OrderController {

    @Autowired
    OrderService orderService;

    @Autowired
    ShopcartService shopcartService;

    @Autowired
    DishesService dishesService;

    @Autowired
    private CouponSeriseService couponSeriseService;

    @Autowired
    private CouponService couponService;

    /**
     * 获取用户的所有订单
     * @return 返回的结果是包装后的订单信息
     */
    @GetMapping("")
    @TokenAuth
    public RespEntity getAllOrder(HttpSession httpSession) {
        UserEntity userEntity = (UserEntity) httpSession.getAttribute("user");
        if(userEntity == null){
            return new RespEntity(
                    RespCode.NO_LOGIN
            );
        }
        int userId = userEntity.getId();
        List<OrderEntity> allOrderForUser = orderService.getAllOrderForUser(userId);
        List viewList = new ArrayList<>();
        for (OrderEntity e : allOrderForUser
        ) {
            OrderVO orderVO = getOrderVO(e);
            viewList.add(orderVO);
        }
        return new RespEntity(
                RespCode.SUCCESS,
                viewList
        );
    }

    private OrderVO getOrderVO(OrderEntity e) {
        OrderVO orderVO = new OrderVO();
        List<OrderItemVO> list = dishesService.getAllOrderItemByOrderId(e.getId());
        orderVO.setList(list);
        orderVO.setOrderEntity(e);
        return orderVO;
    }

    /**
     * 生成订单过程：
     * 0   检查一下是否能产生订单
     * 1.  创建订单
     * 2.  将购物车的内容转为订单项
     * 3.  删除购物车内容
     * 4.
     *
     * @return 生成订单结果
     */
    @PostMapping("")
    @TokenAuth
    public RespEntity addNewOrder(@RequestParam(value = "couponId",required = false)Integer couponSeriesId,HttpSession httpSession) {
        UserEntity userEntity = (UserEntity) httpSession.getAttribute("user");
        if(userEntity == null){
            return new RespEntity(
                    RespCode.NO_LOGIN
            );
        }
        int userId = userEntity.getId();
        List<ShoppingCartEntity> shoppingCartEntities = shopcartService.getUserAllShopcart(userId);
        if (shoppingCartEntities.size() == 0) {
            return new RespEntity(
                    500,
                    "购物车为空"
            );
        }
        //前提判断
        if (!addOrder(userId,couponSeriesId, shoppingCartEntities)) {
            return new RespEntity(
                    RespCode.OUT_OF_SALE
            );
        } else {
            return new RespEntity(
                    RespCode.SUCCESS
            );
        }
    }

    @GetMapping("/{orderId}")
    @TokenAuth
    public RespEntity getOrderItem(@PathVariable int orderId){
        OrderEntity orderEntity = orderService.getOrderById(orderId);
        if (orderEntity == null) {
            return new RespEntity(
                    RespCode.SOURCE_NOT_FOUND
            );
        } else {
            OrderVO vo = getOrderVO(orderEntity);
            return new RespEntity(
                    RespCode.SUCCESS,
                    vo
            );
        }

    }

    @PutMapping("/{orderId}")
    @TokenAuth
    public RespEntity cancelOrder(@PathVariable int orderId,@RequestParam("state")String state , HttpSession httpSession){
        OrderEntity orderById = orderService.getOrderById(orderId);
        if(orderById == null){
            return new RespEntity(
                    RespCode.SOURCE_NOT_FOUND
            );
        }
        //如果存在
        if ("cancel".equals(state) && AdminOrderController.isResult(state, orderById, orderService)) {
            couponService.cancelOrderReturnCoupon(orderById.getUserId(),orderById.getPayId());
            return new RespEntity(
                    RespCode.SUCCESS
            );
        } else {
            return new RespEntity(
                    RespCode.ERROR
            );
        }
    }

    private boolean addOrder(int userId,Integer couponId, List<ShoppingCartEntity> shoppingCartEntities) {
        OrderEntity orderEntity = new OrderEntity();
        orderEntity.setPayId(couponId);
        orderEntity.setUserId(userId);
        OrderEntity order = orderService.createOrder(orderEntity);
        //check前提条件
        for (ShoppingCartEntity e : shoppingCartEntities) {
            DishesEntity dishesEntity = dishesService.getDishesById(e.getDishesId());
            if (e.getNumber() > dishesEntity.getStoreNum()) {
                return false;
            }
        }
        BigDecimal bigDecimal = BigDecimal.ZERO;
        for (ShoppingCartEntity e : shoppingCartEntities) {
            DishesEntity dishesEntity = dishesService.getDishesById(e.getDishesId());
            OrderItemEntity orderItemEntity = new OrderItemEntity();
            orderItemEntity.setOrderId(order.getId());
            orderItemEntity.setDishesId(e.getDishesId());
            orderItemEntity.setNumber(e.getNumber());
            orderItemEntity.setPrice(dishesEntity.getPrice());
            orderService.createOrderItem(orderItemEntity);//创建订单项
            shopcartService.deleteShopcart(e);//购物清空生成订单项
            bigDecimal = bigDecimal.add(dishesEntity.getPrice().multiply(new BigDecimal(e.getNumber())));
        }
        //修改订单内的信息
        orderEntity.setTotalAmount(bigDecimal);
        orderService.updateOrder(orderEntity);
        //
        //更新菜单销量和存货
        for (ShoppingCartEntity e : shoppingCartEntities) {
            DishesEntity dishesEntity = dishesService.getDishesById(e.getDishesId()); //可优化
            dishesEntity.setStoreNum(dishesEntity.getStoreNum() - e.getNumber());
            dishesEntity.setSaleNum(dishesEntity.getSaleNum() + e.getNumber());
            dishesService.saveDishes(dishesEntity);
        }
        //使用优惠券
        if(couponId!=null) {
            CouponSeriesEntity couponSeriesEntity = couponSeriseService.getCouponSeriesById(orderEntity.getPayId());
            if (couponSeriesEntity != null && couponSeriesEntity.getMixLimit().compareTo(orderEntity.getTotalAmount()) < 1) {
                BigDecimal decimal = orderEntity.getTotalAmount().subtract(couponSeriesEntity.getQuota());
                orderEntity.setTotalAmount(decimal);
                couponService.useCoupon(orderEntity.getUserId(), orderEntity.getPayId());
            }
        }
        return true;
    }
}
